﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using COMOSOFT.JobManagement.Froms;
using COMOSOFT.Class;
using COMOSOFT.JobManagement.Report;
using DevExpress.XtraReports.UI;
using System.IO;
using DevExpress.XtraEditors;
using DevExpress.Utils;

namespace COMOSOFT.JobManagement.USC
{
    public partial class UscJobView : UserControl
    {
        Task task;        
        ClassShare cls = new ClassShare("FrmJobView");
        int JID;
        List<string> ListAttachFile = new List<string>();
        Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter adt = new Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter();
        public UscJobView()
        {
            InitializeComponent();            
        }

        public void LoadData(string Type)
        {
            try
            {
                if (task == null || task.Status != TaskStatus.Running)
                {
                    splashScreenManager.ShowWaitForm();
                    gridControl_JobManage.DataSource = null;
                    task = Task.Factory.StartNew(() => sp_JobMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobMenu, ClassShare.Usid, Type));
                    task.ContinueWith(tt => FillTable());
                }
            }
            catch
            { 
            }
        }
        private delegate void dlgFillTable();
        private void FillTable()
        {
            if (InvokeRequired)
            {
                this.Invoke(new dlgFillTable(FillTable));
            }
            else
            {
                gridControl_JobManage.DataSource = dataSet_JobManagement.sp_JobMenu;
                splashScreenManager.CloseWaitForm();
                gridView_JobManage.FocusedRowHandle = 0;
            }
        }

        private void gridView_JobManage_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                string Requester = view.GetRowCellValue(e.ListSourceRowIndex, "Requester").ToString();
                string EID = view.GetRowCellValue(e.ListSourceRowIndex, "EID").ToString();
                string SubStatus = view.GetRowCellValue(e.ListSourceRowIndex, "SubStatus").ToString();
                string Status = view.GetRowCellValue(e.ListSourceRowIndex, "Status").ToString();
                string cc = view.GetRowCellValue(e.ListSourceRowIndex, "CC").ToString();
                if (e.Column.FieldName == "colIcon" && e.IsGetData)
                {

                    if (Status == " Finished")
                        e.Value = imageCollection_Alert.Images[9];
                    else
                    {
                        if (Status == "  Failed")
                            e.Value = imageCollection_Alert.Images[10];
                        else
                        {
                            if (cc != "")
                                e.Value = imageCollection_Alert.Images[7];
                            else
                            {
                                if ((Requester != EID) && SubStatus == "" && (Status == "Pending"))
                                    e.Value = imageCollection_Alert.Images[5];
                                else
                                    e.Value = imageCollection_Alert.Images[6];
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }

        #region [Display Attachfiles]
        private void DisplayAtachfiles(List<string> List, ButtonEdit bnt)
        {
            try
            {
                while (bnt.Properties.Buttons.Count > 1)
                {
                    bnt.Properties.Buttons.RemoveAt(0);
                }
                foreach (string fn in List)
                {
                    if (!File.Exists(ClassShare.lcJobAsign+ fn.ToString()))
                       cls.Dowload(ClassShare.ftpJobAssign, ClassShare.lcJobAsign, fn.ToString());
                    FileInfo finfo = new FileInfo(ClassShare.lcJobAsign + fn);
                    Image img = null;
                    if (finfo.Extension.ToLower() == ".pdf")
                    {
                        img = imageCollection2.Images[2];                        
                    }
                    else if (finfo.Extension.ToLower() == ".xls")
                    {
                        img = imageCollection2.Images[1];
                        
                    }
                    else if (finfo.Extension.ToLower() == ".xlsx")
                    {
                        img = imageCollection2.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".doc")
                    {
                        img = imageCollection2.Images[3];
                    }
                    else if (finfo.Extension.ToLower() == ".docx")
                    {
                        img = imageCollection2.Images[3];
                    }
                    else
                        img = imageCollection2.Images[0];


                    SerializableAppearanceObject serializableAppreanceObje = new DevExpress.Utils.SerializableAppearanceObject();
                    serializableAppreanceObje.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Underline);
                    serializableAppreanceObje.ForeColor = System.Drawing.Color.Blue;
                    serializableAppreanceObje.Options.UseFont = true;
                    serializableAppreanceObje.Options.UseForeColor = true;
                    DevExpress.XtraEditors.Controls.EditorButton b = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, finfo.Name.Substring(0, finfo.Name.Length), -1, true, true, false, DevExpress.XtraEditors.ImageLocation.MiddleLeft, img, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppreanceObje, "", null, null, true);
                    if (JID < 0)
                    {
                        DevExpress.XtraEditors.Controls.EditorButton delete = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, imageCollection1.Images[6], null);
                        delete.Tag = "delete," + fn;
                        bnt.Properties.Buttons.Insert(0, delete);
                    }
                    b.Tag = ClassShare.lcJobAsign + fn;
                    bnt.Properties.Buttons.Insert(0, b);
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void gridView_JobManage_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            GridView view = sender as GridView;
            try
            {
                if (!view.IsGroupRow(e.FocusedRowHandle))
                {
                    JID = Convert.ToInt32(view.GetFocusedDataRow()["JID"]);                  
                    txt_Assigner.Text = view.GetFocusedDataRow()["FullName"].ToString();
                    txt_BeginDate.EditValue = view.GetFocusedDataRow()["CreateDate"];
                    txt_EndDate.EditValue = view.GetFocusedDataRow()["EndDate"];
                    txt_Satatus.Text = view.GetFocusedDataRow()["Status"].ToString();
                    txt_Content.Text = view.GetFocusedDataRow()["Content"].ToString();
                    txt_Title.Text = view.GetFocusedDataRow()["SubJect"].ToString();
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["Image"]) ? "" : view.GetFocusedDataRow()["Image"].ToString()) != "")
                    {
                        if(!File.Exists(ClassShare.lcSystem + view.GetFocusedDataRow()["Image"].ToString()))
                            cls.Dowload(ClassShare.ftpSystem, ClassShare.lcSystem, view.GetFocusedDataRow()["Image"].ToString());
                        byte[] img = System.IO.File.ReadAllBytes(ClassShare.lcSystem + view.GetFocusedDataRow()["Image"].ToString());                       
                        pictureEdit_Avartar.EditValue = img;
                    }
                    ListAttachFile.Clear();
                    DataTable dtb = adt.GetData(JID);
                    int numrow = dtb.Rows.Count;
                    if (numrow > 0)
                    {
                        for (int i = 0; i < numrow; i++)
                        {
                            ListAttachFile.Add(dtb.Rows[i]["Filename"].ToString());
                        }
                    }
                    DisplayAtachfiles(ListAttachFile, bnt_FileAttach);
                }
            }
            catch
            {
            }
        }

        private void bnt_ViewDetails_Click(object sender, EventArgs e)
        {
            if (JID > 0)
            {
                FrmJobManagement frmJobMnt = new FrmJobManagement(JID, true);
                frmJobMnt.Show();
                frmJobMnt.LoadData();
            }
        }

        private void gridView_JobManage_DoubleClick(object sender, EventArgs e)
        {
            FrmJobManagement frmJobMnt = new FrmJobManagement(JID, true);
            frmJobMnt.Show();
            frmJobMnt.LoadData(); 
        }  
    
        private void bnt_Print_Click(object sender, EventArgs e)
        {
            if (JID > 0)
            {
                JobPrintItem rptItem = new JobPrintItem(JID, ClassShare.Usid);
                ReportPrintTool print = new ReportPrintTool(rptItem);
                print.ShowRibbonPreview(DevExpress.LookAndFeel.UserLookAndFeel.Default);
            }
        }

        private void bnt_FileAttach_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Tag.ToString()!="space")
                System.Diagnostics.Process.Start(e.Button.Tag.ToString());
        }   
    }
}
